//
//  PlayManager.m
//  Leisure
//
//  Created by 大展 on 16/4/21.
//  Copyright © 2016年 张展. All rights reserved.
//

#import "PlayManager.h"

@interface PlayManager ()

@property (nonatomic, strong)AVPlayer *player; // 专门用来处理音频的

@property (nonatomic,retain)NSTimer *timer;
@end

@implementation PlayManager

// 单例 只被初始化一次
+ (PlayManager *)sharedManager {

    static PlayManager *handle = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        handle = [[PlayManager alloc]init];
    });
    return handle;
}

// 重写init方法，当对象被初始化的时候去创建player对象
- (instancetype)init
{
    self = [super init];
    if (self) {

        self.player = [[AVPlayer alloc]init];
    }
    return self;
}

// 准备根据url去播放电台（仅仅是准备）
- (void)prepareToPlayRadioWithUrl:(NSString *)url {

    // 如果网址为空直接跳出
    if (!url) {

        return;
    }
    // 根据url去创建一个avplayItem对象
    AVPlayerItem *item = [[AVPlayerItem alloc]initWithURL:[NSURL URLWithString:url]];
    [self.player replaceCurrentItemWithPlayerItem:item];
}
// 播放电台
- (void)playRadio {

    [self.player play];
}

// 暂停电台
- (void)pauseRadio {

    [self.player pause];
}

//获取音乐时间
-(NSInteger)fetchCurrentTime{
    
    CMTime time = self.player.currentTime;
    
    //获取当前播放秒数 time.value/time.timescale
    if (time.timescale == 0) {
        return 0;
    }
    
    return  time.value/time.timescale;
    
}

//获取总时间
-(NSInteger)fetchTotalTime{
    
    CMTime time = self.player.currentItem.duration;
    
    //获取当前播放秒数 time.value/time.timescale
    if (time.timescale == 0) {
        return 0;
    }
    
    return  time.value/time.timescale;
    
}

//获取播放进度
-(CGFloat)fetchPlayProgress{
    
    //当前时间
    CGFloat currentime = (CGFloat)[self fetchCurrentTime];
    //总时间
    CGFloat totaltime = [self fetchTotalTime];
    
    //获取进度（当前时间/总时间）
    return currentime/totaltime;
}

//把时间转换成字符串
-(NSString *)changTimeToString:(NSInteger)senders{
    
    //获取分数
    NSInteger min = senders/60;
    
    //获取余数
    NSInteger sec = senders%60;
    
    return [NSString stringWithFormat:@"%02ld:%02ld",min,sec];
    
}


//开启定时器
-(void)startTimer{
    
    //如果当前timer已经被初始化，便不再初始化
    if (self.timer) {
        return;
    }
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    
}

//关闭定时器
-(void)closeTImer{
    
    //吧timer废除
    [self.timer invalidate];
    
    //把timer滞空
    self.timer = nil;
    
    
}

//定时器方法
-(void)timerAction{
    if (self.delegate &&[self.delegate respondsToSelector:@selector(playManagerFechRestTime:progress:)]){
        
        NSInteger restTime = [self fetchTotalTime] - [self fetchCurrentTime];
        
        [self.delegate playManagerFechRestTime:[self changTimeToString:restTime] progress:[self fetchPlayProgress]];
    }
}








@end
